package com.video.service.impl;

import com.api.client.IdClient;
import com.api.client.PluginClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.domain.dto.SupplierAddDTO;
import com.common.domain.po.Plugin;
import com.common.domain.po.Supplier;
import com.common.domain.vo.SupplierListByPageVO;
import com.common.exception.CodeAndMsg;
import com.common.exception.JavaSmException;
import com.common.utils.BeanUtils;
import com.common.utils.Convert;
import com.video.mapper.SupplierMapper;
import com.video.service.SupplierService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.File;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Random;

/**
 * @author 路亚
 * @version 0.1
 * @className SupplierServiceImpl
 * @description
 * @date 2025/1/3 15:56
 * @since jdk11
 */
@Service
@RequiredArgsConstructor
public class SupplierServiceImpl extends ServiceImpl<SupplierMapper, Supplier> implements SupplierService {

    private final IdClient idClient;

    private final SupplierMapper supplierMapper;

    private static String SUPPLIER_TYPE = "supplier";

    private final PluginClient pluginClient;

    @Override
    public void add(SupplierAddDTO supplierAddDTO) {
        Supplier supplier = BeanUtils.copyBean(supplierAddDTO, Supplier.class, (source, target) -> {
            target.setId(idClient.getLongKeyInterval(SUPPLIER_TYPE));
            target.setVideoNum(0);
            target.setStatus(0);
        });
        save(supplier);
    }

    @Override
    public SupplierListByPageVO listByPage(String supplierName, Integer page) {
        Page<Supplier> supplierPage = new Page<>();
        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(supplierName)){
            queryWrapper.like("supplier_name", supplierName);
        }
        Page<Supplier> resultPage = supplierMapper.selectPage(supplierPage, queryWrapper);
        return new SupplierListByPageVO(resultPage.getTotal(), page, resultPage.getRecords());
    }

    @Override
    public void deleteById(Long id) {
        Supplier supplier = supplierMapper.byId(id);
        if (supplier.getVideoNum() == 0){
            supplierMapper.removeById(id);
        }else if (supplier.getVideoNum() > 0){
            supplierMapper.deleteById(id);
        }
        System.out.println("supplier = " + supplier);
    }


    @Override
    public BigDecimal getMoney(Long id, Long pluginId) {
        // 根据供应商id，查询短剧信息，并计算短剧信息带来的收益
        // TODO：需求暂时没有说明收益如何计算，这里使用100 - 10000的随机数先做收益
        // 创建Random对象
        Random random = new Random();
        // 生成一个100到10000之间的随机数
        int randomNumber = 100 + random.nextInt(10000 - 100);
        // 根据插件id，获取插件信息
        Plugin plugin = pluginClient.getById(pluginId);
        // 根据插件提供的信息，就可以远程调用jar包里的方法了
        // 创建一个URL数组
        try {
            File file = new File(plugin.getPath());
            URL[] urls = {file.toURI().toURL()};
            // 创建URLClassLoader对象，并指定扫描路径
            URLClassLoader urlClassLoader = new URLClassLoader(urls);
            // 这时候urlClassLoader的parent就是AppClassLoader

            // 利用反射执行jar包中的代码
            Class<?> aClass = urlClassLoader.loadClass(plugin.getClassName());
            Object obj = aClass.newInstance();
            Method method = aClass.getMethod(plugin.getMethodName(), BigDecimal.class);
            return (BigDecimal) method.invoke(obj, new BigDecimal(randomNumber));
        } catch (Exception e){
            throw new JavaSmException(CodeAndMsg.PLUGIN_ERROR);
        }
    }
}
